package com.example.byd

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.media.AudioAttributes
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.*
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import android.util.Log
import android.view.WindowManager
import androidx.annotation.RequiresApi
import androidx.preference.PreferenceManager
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Process
import java.util.*
import java.util.concurrent.TimeUnit



class GetLogCatService : Service(){
    private val notificationId = "callingChannelId"
    private val notificationName = "callingChannelName"
    private var winmager:WindowManager? = null
    private var mHandler:Handler?=null
    private var tnewview:RadarView?=null
 
    @RequiresApi(Build.VERSION_CODES.O)
    private fun getNotification(): Notification {
        val builder = Notification.Builder(this,notificationId)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("byd宋加服务")
            .setContentText("服务正在运行")
//        //设置Notification的ChannelID,否则不能正常显示
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            builder.setChannelId(notificationId)
//        }
        return builder.build()
    }
    private fun startspeak(line:String) {
        val intent = Intent()
        intent.action = "com.songjia.speak"
        intent.setPackage("com.sogou.map.android.maps")
        intent.putExtra("data", line)
        sendBroadcast(intent)
        Log.i("bydautosong","intent 发送成 内容是${line}")
    }
    //其中onCreate()方法会在Service创建的 时候调用
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate() {
        super.onCreate()
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        //创建NotificationChannel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                notificationId,
                notificationName,
                NotificationManager.IMPORTANCE_HIGH
            )
            notificationManager.createNotificationChannel(channel)
        }
        startForeground(1, getNotification())
        winmager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        mHandler = Handler(Looper.getMainLooper());
        Log.d("bydautosong", "yangyangyang onCreate executed")

    }
    //onStartCommand()方法会在每次Service启动的时候调用
    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        Log.d("bydautosong", "yangyangyang onStartCommand executed")
        Log.d("bydautosong", "服务启动 雷达播报  ${switch_radar}")
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this /* Activity context */)
        Thread {

            Thread.sleep(1000)
            var welcome_string =  sharedPreferences.getString("welcome-string", "")
            if (welcome_string != null) {
                if(welcome_string.length==0){
                    welcome_string="尊贵的比亚迪车主，小迪在此等候多时了。赶紧来开我呀！"
                }
            }else{
                welcome_string="尊贵的比亚迪车主，小迪在此等候多时了。赶紧来开我呀！"
            }
            if( welcome_string != "不要呀") {
                startspeak(welcome_string)
                Log.i("bydautosong", "播报欢迎语${welcome_string}")
            }else{
                Log.i("bydautosong", "不播报欢迎语${welcome_string}")
            }
            while (true){
                val mLogcatProc: Process
                val reader: BufferedReader
                var carspeed= 0F

//                tts!!.speak("BYD宋加助手开始监控系统进程", TextToSpeech.QUEUE_FLUSH,null,"")
                Log.d("bydautosong", "BYD宋加助手开始监控系统进程")
                try {
                    //获取logcat日志信息
//                线程开启以后Runtime主要用于过滤logcat信息，这里主要说一下里面的参数
//                "logcat"不用说了吧，我们就是要监听它
//                "Mytest" 表示监听的Tag 这里以上面点击按钮输出的LOG信息为例。
//                "I"表示监听的Log类型，当然这里还可以写其它类型 。VERBOSE(v) 、DEBUG(d)、 INFO(i)、 WARN(w)、 ERROR(e)， 不过须要与监听的与Tag一一对称才可以。
//                "*:s"表示监听所有的信息，这里表示只要tag是Mytest ,Logcat类型为i 的 所有Log都会被获取到。

                    mLogcatProc = Runtime.getRuntime()
                        .exec(arrayOf("logcat", "-v" , "epoch" , "BYDAutoRadarDevice:D *:S,BYDAutoLightDevice:D *:S,BYDAutoADASDevice:D *:S,bydsongtts:D *:S,BYDAutoInstrumentDevice:D *:S,AVC_AbsBYDAutoSpeedListener:D *:S,m_tag:D *:S"))
                    reader = BufferedReader(InputStreamReader(mLogcatProc.inputStream))
                    var line: String
                    while (  reader.readLine().also {
                            if(it==null){
                                line=""
                            }else{
                                line = it
                            }
                        } != null) {
//
//                    Log.i("bydautosong", "车速限制："+speed_limit);
                        if(line==""){
                            continue
                        }


                        val switch_dang=sharedPreferences.getBoolean("switch_dang", true)
                        val switch_radar = sharedPreferences.getBoolean("switch_radar", true)
                        val switch_open_acc = sharedPreferences.getBoolean("switch_open_acc", true)
                        val speed_limit = sharedPreferences.getString("speed_limit","120")?.toFloat()
                        val switch_open_autostop = sharedPreferences.getBoolean("switch_open_autostop", true)

                        if(switch_dang==true){

                            if(line.indexOf("onGearboxAutoModeTypeChanged: level:1")>0){
                                Log.i("bydsongtts", "驻车档")//
                                continue
                            }

                            if(line.indexOf("onGearboxAutoModeTypeChanged: level:3")>0){
                                Log.i("bydsongtts", "N档,注意溜车")//
                                continue
                            }
                            if(line.indexOf("onGearboxAutoModeTypeChanged: level:4")>0){
                                Log.i("bydsongtts", "前进档")//
                                continue
                            }
                            if(line.indexOf("onGearboxAutoModeTypeChanged: level:2")>0){
                                Log.i("bydsongtts", "倒档")//
                                continue
                            }

                        }


                        if(line.indexOf("onSpeedChanged() value=")>0){
                            val last_speed=carspeed
                            carspeed=line.split("onSpeedChanged() value= ")[1].toFloat()

                            if(carspeed> speed_limit!! &&last_speed<speed_limit ){
                                val speed:Int = speed_limit.toInt()

                                Log.i("bydsongtts", "当前车速超过${speed}")
                            }
//
//                        Log.i("bydautosong", "当前车速${carspeed}")
                            continue
                        }

                        if(line.indexOf("closefuchuang bydautosong")>0){


                            val radar = hashMapOf <String, String>()
                            radar["left_front"] = "150"
                            //右前
                            radar["right_front"] = "150"
                            //左后
                            radar["left_rear"] = "150"
                            //又后
                            radar["right_rear"] = "150"
                            //左侧
                            radar["left"] ="150"
                            //右侧
                            radar["right"] = "150"
                            radar["front_left"] = "150"
                            radar["front_right"] = "150"
                            //正后
                            radar["middle_rear"] ="150"




                            mHandler?.post(Runnable {
                                tnewview?.rmview()
                                if(tnewview == null){
                                    tnewview= winmager?.let { RadarView(it, baseContext,radar) }
                                }else{
                                    tnewview!!.updatedata(radar)
                                }

                                tnewview?.addview(true)
                                Log.e("bydautosong","nnnnnnnnnnnnnnnnnnn")
                            })


                            continue
                        }
                        Log.i("bydautosong", "获取到日志：$line")
                        if(line.indexOf("bydsongtts")>0){
                            Log.i("bydautosong", "获取到日志："+line)
                            val text=line.split("bydsongtts:")[1]
                            startspeak(text)
                        }

                        if (switch_merageisopen==true){
                            if (line.indexOf("this is a test") > 0) {
                                //logcat打印信息在这里可以监听到
                                // 使用looper 把给界面一个显示
                                Log.i("bydautosong", "this is a test 被发现")
                            }
                        }
                        if(switch_open_acc==true){

                            //车辆停止  启动是1 停止是2
//                        if (line.indexOf("event_type =12200046") > 0) {
//                            val isopen=line.split("event_type =12200046,")[1].split("=")[1]
//                            Log.i("bydautosong","定速巡航状态${isopen}")
//                            tts!!.setSpeechRate(4f)
//                            tts!!.speak("定速巡航状态${isopen}", TextToSpeech.QUEUE_FLUSH,null,"")
//                        }

                            if (line.indexOf("event_type =26100038") > 0) {
                                val isopen=line.split("event_type =26100038,")[1].split("=")[1]
                                if(isopen !=" 3"){
                                    continue
                                }
                                if(carspeed>10){
                                    val saystr="定速巡航发生改变"
                                    Log.i("bydautosong",saystr)
                                    startspeak(saystr)
                                }
                            }
                        }
                        if(switch_open_autostop==true){

                            if (line.indexOf("event_type =12200046, value = 2") > 0) {
                                    val saystr="自动驻车已开启"
                                    Log.i("bydautosong",saystr)
                                startspeak(saystr)
                            }
                        }
                        if(switch_radar==true){
                            if (line.indexOf("getAllRadarDistance format:") > 0) {
                                val arrtest=line.split("getAllRadarDistance format:")
                                Log.e("bydautosong","字符串被拆分:"+arrtest[1])
                                val radar = hashMapOf <String, String>()
                                radar["left_front"] = arrtest[1].split(",")[0].split(" ")[4]
                                //右前
                                radar["right_front"] = arrtest[1].split(",")[1].split(" ")[4]
                                //左后
                                radar["left_rear"] = arrtest[1].split(",")[2].split(" ")[4]
                                //又后
                                radar["right_rear"] = arrtest[1].split(",")[3].split(" ")[4]
                                //左侧
                                radar["left"] = arrtest[1].split(",")[4].split(" ")[3]
                                //右侧
                                radar["right"] = arrtest[1].split(",")[5].split(" ")[3]
                                radar["front_left"] = arrtest[1].split(",")[6].split(" ")[4]
                                radar["front_right"] = arrtest[1].split(",")[7].split(" ")[4]
                                //正后
                                radar["middle_rear"] = arrtest[1].split(",")[8].split(" ")[5]
                                var postion:String

                                var text:String=""
                                var lastdist:Int=200
                                var lastpostion:String=""

                                mHandler?.post(Runnable {
                                    tnewview?.rmview()
                                    if(tnewview == null){
                                        tnewview= winmager?.let { RadarView(it, baseContext,radar) }
                                    }else{
                                        tnewview!!.updatedata(radar)
                                    }

                                    tnewview?.addview(true)
                                    Log.e("bydautosong","nnnnnnnnnnnnnnnnnnn")
                                })


                            }


                            if (line.indexOf("getAllRadarDistance:") > 0) {
                                //logcat打印信息在这里可以监听到
                                // 使用looper 把给界面一个显示
                                val arrtest=line.split("getAllRadarDistance:")
                                Log.e("bydautosong","字符串被拆分:"+arrtest[1])
                                val radar = hashMapOf <String, String>()
//        左前
                                radar["left_front"] = arrtest[1].split(",")[0].split(" ")[4]
                                //右前
                                radar["right_front"] = arrtest[1].split(",")[1].split(" ")[4]
                                //左后
                                radar["left_rear"] = arrtest[1].split(",")[2].split(" ")[4]
                                //又后
                                radar["right_rear"] = arrtest[1].split(",")[3].split(" ")[4]
                                //左侧
                                radar["left"] = arrtest[1].split(",")[4].split(" ")[3]
                                //右侧
                                radar["right"] = arrtest[1].split(",")[5].split(" ")[3]
                                radar["front_left"] = arrtest[1].split(",")[6].split(" ")[4]
                                radar["front_right"] = arrtest[1].split(",")[7].split(" ")[4]
                                //正后
                                radar["middle_rear"] = arrtest[1].split(",")[8].split(" ")[5]
                                var postion:String

                                var text:String=""
                                var lastdist:Int=200
                                var lastpostion:String=""

//                                Looper.prepare()
//                                val tview= winmager?.let { RadarView(it, baseContext,radar) }
//                                if (tview != null) {
//                                    tview.addview()
//                                }
//                                Looper.loop();

                                mHandler?.post(Runnable {
                                            tnewview?.rmview()
                                            if(tnewview == null){
                                                tnewview= winmager?.let { RadarView(it, baseContext,radar) }
                                            }else{
                                                tnewview!!.updatedata(radar)
                                            }

                                            tnewview?.addview(false)
                                    Log.e("bydautosong","nnnnnnnnnnnnnnnnnnn")
                                })
                                for(ra in radar.entries ){
                                    if(ra.value == "150"){
                                        continue
                                    }
//                                    Thread.sleep(200)
                                    when(ra.key){
                                        "left_front" ->{postion = "左前"}
                                        "right_front" ->{postion = "右前"}
                                        "left_rear" ->{postion = "左后"}
                                        "right_rear" ->{postion = "右后"}
                                        "left" ->{postion = "左侧"}
                                        "right" ->{postion = "右侧"}
                                        "front_left" ->{postion = "左前1"}
                                        "front_right" ->{postion = "右前1"}
                                        "middle_rear" ->{postion = "后侧"}
                                        else ->  {postion = "出问题了"}
                                    }
                                    if(lastdist>ra.value.toInt()){
                                        lastdist=ra.value.toInt()
                                        lastpostion=postion
                                    }


                                    Log.e("bydautosong","字符串提取:"+"${ra.key}->${ra.value}")

                                    //   tts!!.speak(text, TextToSpeech.QUEUE_FLUSH, params,"")

                                }
                                if(lastdist != 200){
                                    text="${lastpostion}$lastdist"
                                    startspeak(text)
                                }

                            }
                        }
                    }

                } catch (e: Exception) {

                    Log.e("bydautosong","异常退出:"+System.err.toString())
                    Log.e("bydautosong", System.err.toString())
                    e.printStackTrace()
                }
            }
        }.start()
        return super.onStartCommand(intent, flags, startId)
    }

    //onDestroy()方法 会在Service销毁的时候调用
    override fun onDestroy() {
        super.onDestroy()
        Log.d("bydautosong", "yangyangyang onDestroy executed")

    }

    override fun onBind(p0: Intent?): IBinder? {
        TODO("Not yet implemented")
    }
}